package com.example.yblin.hello24;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.ImageView;
import android.widget.PopupMenu;
import android.widget.TextView;
import android.widget.Toast;

import com.example.yblin.hello24.DataUtils.GameUtil;
import com.example.yblin.hello24.DataUtils.NetUtil;

import java.util.Timer;
import java.util.TimerTask;

public class StageGameActivity extends AppCompatActivity implements View.OnClickListener {


    private TextView btNum1;
    private TextView btNum2;
    private TextView btNum3;
    private TextView btNum4;
    private TextView btAdd;
    private TextView btSubtract;
    private TextView btMultiply;
    private TextView btDivide;
    private TextView btLeftBracket;
    private TextView btRightBracket;
    private TextView tvExpression;
    private TextView btReinput;
    private TextView btAbandon;
    private TextView btSubmit;
    private TextView tvTitle;
    private TextView btBackspace;
    private TextView tvTime;
    private Timer timer;
    private int time = 60;
    private MHandler mHandler;

    private synchronized void setTime(int time) {
        this.time = time;
    }

    private synchronized int getTime() {
        return time;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_stage_game);

        btNum1 = findViewById(R.id.textView_stage_num1);
        btNum1.setOnClickListener(this);
        btNum2 = findViewById(R.id.textView_stage_num2);
        btNum2.setOnClickListener(this);
        btNum3 = findViewById(R.id.textView_stage_num3);
        btNum3.setOnClickListener(this);
        btNum4 = findViewById(R.id.textView_stage_num4);
        btNum4.setOnClickListener(this);


        btAdd = findViewById(R.id.textView_stage_add);
        btAdd.setOnClickListener(this);
        btSubtract = findViewById(R.id.textView_stage_subtract);
        btSubtract.setOnClickListener(this);
        btMultiply = findViewById(R.id.textView_stage_multiply);
        btMultiply.setOnClickListener(this);
        btDivide = findViewById(R.id.textView_stage_divide);
        btDivide.setOnClickListener(this);
        btLeftBracket = findViewById(R.id.textView_stage_left_bracket);
        btLeftBracket.setOnClickListener(this);
        btRightBracket = findViewById(R.id.textView_stage_right_bracket);
        btRightBracket.setOnClickListener(this);

        tvExpression = findViewById(R.id.textView_stage_expression);
        btReinput = findViewById(R.id.textView_stage_reinput);
        btReinput.setOnClickListener(this);
        btSubmit = findViewById(R.id.textView_stage_submit);
        btSubmit.setOnClickListener(this);
        btAbandon = findViewById(R.id.textView_stage_abandon);
        btAbandon.setOnClickListener(this);
        tvTitle = findViewById(R.id.textView_stage_title);

        btBackspace = findViewById(R.id.textView_stage_backspace);
        btBackspace.setOnClickListener(this);

        mHandler = new MHandler(this);
        tvTime = findViewById(R.id.textView_stage_time);

        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                setTime(getTime() - 1);
                if (getTime() > 0) {
                    mHandler.sendEmptyMessage(MHandler.MSG_GO);
                } else {
                    mHandler.sendEmptyMessage(MHandler.MSG_END);
                    timer.cancel();
                }
            }
        }, 0, 1000);

        getPageData();
    }

    class MHandler extends Handler {

        public static final int MSG_GO = 0;
        public static final int MSG_END = 1;

        private Context context;

        public MHandler(Context context) {
            this.context = context;
        }

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_GO:
                    tvTime.setText(getTime() + "");
                    break;
                case MSG_END:
                    tvTime.setText(getTime() + "");
                    new StageGameAbandonAsync().execute();
                    break;
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.textView_stage_num1:
                if (!GameUtil.numbers[0][0].selected) {//在数字没有被选中的前提下
                    GameUtil.numbers[0][0].selected = true;//数字被选中
                    GameUtil.expression[0].add(GameUtil.numbers[0][0].number);//数字被添加进表达式
                    btNum1.setAlpha(0.5f);//UI设置被选中
                }//数字被选中无响应
                break;
            case R.id.textView_stage_num2:
                if (!GameUtil.numbers[0][1].selected) {//在数字没有被选中的前提下
                    GameUtil.numbers[0][1].selected = true;//数字被选中
                    GameUtil.expression[0].add(GameUtil.numbers[0][1].number);//数字被添加进表达式
                    btNum2.setAlpha(0.5f);//UI设置被选中
                    //tvExpression.setText(GameUtil.toString(GameUtil.expression[0]));//UI表达式刷新
                }//数字被选中无响应
                break;
            case R.id.textView_stage_num3:
                if (!GameUtil.numbers[0][2].selected) {//在数字没有被选中的前提下
                    GameUtil.numbers[0][2].selected = true;//数字被选中
                    GameUtil.expression[0].add(GameUtil.numbers[0][2].number);//数字被添加进表达式
                    btNum3.setAlpha(0.5f);//UI设置被选中
                }//数字被选中无响应
                break;
            case R.id.textView_stage_num4:
                if (!GameUtil.numbers[0][3].selected) {//在数字没有被选中的前提下
                    GameUtil.numbers[0][3].selected = true;//数字被选中
                    GameUtil.expression[0].add(GameUtil.numbers[0][3].number);//数字被添加进表达式
                    btNum4.setAlpha(0.5f);//UI设置被选中
                }//数字被选中无响应
                break;
            case R.id.textView_stage_add:
                GameUtil.expression[0].add(GameUtil.ADD);
                break;
            case R.id.textView_stage_subtract:
                GameUtil.expression[0].add(GameUtil.SUB);
                break;
            case R.id.textView_stage_multiply:
                GameUtil.expression[0].add(GameUtil.MUL);
                break;
            case R.id.textView_stage_divide:
                GameUtil.expression[0].add(GameUtil.DIV);
                break;
            case R.id.textView_stage_left_bracket:
                GameUtil.expression[0].add(GameUtil.LEFT);
                break;
            case R.id.textView_stage_right_bracket:
                GameUtil.expression[0].add(GameUtil.RIGHT);
                break;
            case R.id.textView_stage_reinput:
                GameUtil.expression[0].clear();//表达式清空
                GameUtil.numbers[0][0].selected = false;//数字全不选中
                GameUtil.numbers[0][1].selected = false;
                GameUtil.numbers[0][2].selected = false;
                GameUtil.numbers[0][3].selected = false;
                btNum1.setAlpha(1);
                btNum2.setAlpha(1);
                btNum3.setAlpha(1);
                btNum4.setAlpha(1);
                //R
                break;
            case R.id.textView_stage_submit:
                btSubmit.setEnabled(false);
                new StageGameSubmitAsync().execute();
                break;
            case R.id.textView_stage_backspace:
                if (GameUtil.expression[0].size() > 0) {
                    int index = GameUtil.expression[0].size() - 1;
                    int num = GameUtil.expression[0].get(index);
                    if (num != GameUtil.ADD && num != GameUtil.SUB
                            && num != GameUtil.MUL && num != GameUtil.DIV
                            && num != GameUtil.LEFT && num != GameUtil.RIGHT) {
                        for (int i = 0; i < 4; i++) {
                            if (GameUtil.numbers[0][i].number == num && GameUtil.numbers[0][i].selected) {//如果被删除的数字被选中
                                GameUtil.numbers[0][i].selected = false;//数字取消选中
                                switch (i) {
                                    case 0:
                                        btNum1.setAlpha(1);
                                        break;
                                    case 1:
                                        btNum2.setAlpha(1);
                                        break;
                                    case 2:
                                        btNum3.setAlpha(1);
                                        break;
                                    case 3:
                                        btNum4.setAlpha(1);
                                        break;
                                }
                                break;
                            }
                        }
                    }
                    GameUtil.expression[0].remove(index);
                }
                break;
            case R.id.textView_stage_abandon:
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("确认放弃")
                        .setMessage("你真的要放弃吗？")
                        .setPositiveButton("放弃", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                btAbandon.setEnabled(false);
                                new StageGameAbandonAsync().execute();
                            }
                        })
                        .setNegativeButton("继续", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                            }
                        });
                AlertDialog dialog = builder.create();
                dialog.show();

                break;
        }
        tvExpression.setText(GameUtil.toString(GameUtil.expression[0], GameUtil.USAGE_FOR_SHOW));//UI表达式刷新
    }

    @Override
    public void onBackPressed() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("确认退出？")
                .setMessage("你真的要退出吗？所有结果将不会保存!")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        StageGameActivity.super.onBackPressed();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                    }
                });
        AlertDialog dialog = builder.create();
        dialog.show();
    }

    public void getPageData() {
        tvTitle.setText("第" + (GameUtil.correctNumber + 1)  + "题");
        //btNum1.setText("" + GameUtil.numbers[pageId][0].number);
        int number = 0;
        number = (GameUtil.numbers[0][0].number - 1) * 4 + ((int) (Math.random() * 4));//获取牌面数字，乘以4后得到黑桃+牌面数字，加0-3得到随机4色
        btNum1.setBackground(getDrawable(GameUtil.poker[number]));
        if (GameUtil.numbers[0][0].selected) {
            btNum1.setAlpha(0.5f);
        } else {
            btNum1.setAlpha(1);
        }

        number = (GameUtil.numbers[0][1].number - 1) * 4 + ((int) (Math.random() * 4));//获取牌面数字，乘以4后得到黑桃+牌面数字，加0-3得到随机4色
        btNum2.setBackground(getDrawable(GameUtil.poker[number]));
        if (GameUtil.numbers[0][1].selected) {
            btNum2.setAlpha(0.5f);
        } else {
            btNum2.setAlpha(1);
        }

        number = (GameUtil.numbers[0][2].number - 1) * 4 + ((int) (Math.random() * 4));//获取牌面数字，乘以4后得到黑桃+牌面数字，加0-3得到随机4色
        btNum3.setBackground(getDrawable(GameUtil.poker[number]));
        if (GameUtil.numbers[0][2].selected) {
            btNum3.setAlpha(0.5f);
        } else {
            btNum3.setAlpha(1);
        }

        number = (GameUtil.numbers[0][3].number - 1) * 4 + ((int) (Math.random() * 4));//获取牌面数字，乘以4后得到黑桃+牌面数字，加0-3得到随机4色
        btNum4.setBackground(getDrawable(GameUtil.poker[number]));
        if (GameUtil.numbers[0][3].selected) {
            btNum4.setAlpha(0.5f);
        } else {
            btNum4.setAlpha(1);
        }

        tvExpression.setText(GameUtil.toString(GameUtil.expression[0], GameUtil.USAGE_FOR_SHOW));
    }


    public class StageGameAbandonAsync extends AsyncTask<Void, Void, Integer> {
        @Override
        protected Integer doInBackground(Void... voids) {
            return GameUtil.stageEnd(StageGameActivity.this);
        }

        @Override
        protected void onPostExecute(Integer result) {
            btAbandon.setEnabled(true);
            if (result == NetUtil.CODE_OK) {
                AlertDialog.Builder builder = new AlertDialog.Builder(StageGameActivity.this);
                builder.setTitle("闯关结束！")
                        .setMessage("本次闯关：" + GameUtil.correctNumber)
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                StageGameActivity.this.finish();
                            }
                        });
                builder.setCancelable(false);

                AlertDialog dialog = builder.create();
                dialog.show();
            }
        }
    }


    public class StageGameSubmitAsync extends AsyncTask<Void, Void, Integer> {
        @Override
        protected Integer doInBackground(Void... voids) {
            return GameUtil.stageNext(StageGameActivity.this);
        }

        @Override
        protected void onPostExecute(Integer result) {
            btSubmit.setEnabled(true);
            if (result == 0) {
                AlertDialog.Builder builder = new AlertDialog.Builder(StageGameActivity.this);
                builder.setTitle("挑战失败")
                        .setMessage("本次闯关：" + GameUtil.correctNumber)
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                StageGameActivity.this.finish();
                            }
                        });
                builder.setCancelable(false);

                AlertDialog dialog = builder.create();
                dialog.show();
            } else {
                setTime(60);
                getPageData();
            }
        }
    }


    
}
